package com.sy.api;

/**
 * @className: PayController
 * @author: Mr.Liu
 * @date: 2025/11/11 16:45
 * @Version: 1.0
 * @description:
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sy.ResultVO;
import com.sy.pojo.Orders;
import com.sy.service.AlipayService;
import com.sy.service.OrdersService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付相关接口，供前端调用
 */
@RestController
@RequestMapping("/pay")
@RequiredArgsConstructor
@Slf4j
public class PayController {
    private final AlipayService alipayService;
    private final OrdersService ordersService;

    /**
     * 创建订单并获取支付宝二维码
     * @param userId 用户ID
     * @param courseId 课程ID（用于支付后跳转回课程页面）
     * @param amount 支付金额
     * @param subject 订单标题
     * @return 包含二维码链接、订单号、课程ID的map
     */
    @GetMapping("/createAlipayOrder")
    @Operation(description = "创建订单并生成支付二维码")
    public Map<String, String> createAlipayOrder(
            @RequestParam Integer userId,
            @RequestParam Integer courseId,
            @RequestParam BigDecimal amount,
            @RequestParam String subject) throws Exception {
        // 1. 调用支付服务生成二维码
        String qrCodeUrl = alipayService.createQrCode(userId, courseId, amount, subject);

        // 2. 获取刚创建的订单号（根据用户ID和课程ID查询最新订单）
        Orders latestOrder = ordersService.getOne(
                new QueryWrapper<Orders>()
                        .eq("user_id", userId)
                        .eq("course_id", courseId)
                        .orderByDesc("create_time")
                        .last("limit 1")
        );

        // 3. 封装返回数据（供前端跳转和轮询使用）
        Map<String, String> result = new HashMap<>();
        result.put("qrCodeUrl", qrCodeUrl);       // 二维码链接
        result.put("orderNumber", latestOrder.getOrderNumber()); // 订单号
        result.put("courseId", courseId.toString()); // 课程ID（支付后跳转用）
        return result;
    }

    /**
     * 查询支付状态
     * @param orderNumber 订单号
     * @return true=已支付，false=未支付
     */
    @GetMapping("/queryPayStatus")
    public boolean queryPayStatus(@RequestParam String orderNumber) throws Exception {
        log.info("支付订单入参:{}",orderNumber);
        return alipayService.queryPayStatus(orderNumber);
    }
    /**
     * 查询支付状态
     * @param userId 用户id
     * @param courseId 课程id
     * @return true=已支付，false=未支付
     */
    @GetMapping("/queryCourseInOrdersStatus")
    public ResultVO<Object> queryOrdersStatus(
                                     @RequestParam Integer userId,
                                     @RequestParam Integer courseId) throws Exception {
        log.info("查询课程在订单状态的入参,userId:{},courseId:{}",userId,courseId);
        if(userId==null){
            return ResultVO.error("用户id不能是空");
        }
        if(courseId==null){
            return ResultVO.error("课程id不能是空");
        }
        boolean flag = ordersService.queryOrdersStatusById(userId, courseId);
        return ResultVO.success(flag);
    }
}
